﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;

namespace SilverlightControls.Designer
{
    public class FormContent: ContentControl
    {
        ScrollViewer _layoutRoot;
        Grid _mainGrid;
        static readonly Type _thisType = typeof(FormContent);

        public void AddChild(FormItem element)
        {
            element.Name = "FormItem" + _mainGrid.Children.Count;
            element.Element.Name = element.Element.GetType().Name + _mainGrid.Children.Count;
            element.Left = 0;
            element.Top = 0;
            element.Click += element_MouseLeftButtonDown;
            _mainGrid.Children.Add(element); 
        }

        private FormItem _currentElement;
        public PropertyGrid PropertyGrid { get; set; }

        void element_MouseLeftButtonDown(object sender, EventArgs e)
        {
            if (_currentElement != null)
                _currentElement.Effect = null;
            _currentElement = sender as FormItem;
            if (_currentElement != null)
                _currentElement.Effect = new DropShadowEffect() { Color = SystemColors.ActiveCaptionColor, Direction = 5, ShadowDepth = 5, BlurRadius = 5, Opacity = 30 };
            if (PropertyGrid != null && _currentElement != null)
                PropertyGrid.SelectedObject = _currentElement.Element;
        }

        #region FormContent Text

        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), _thisType, new PropertyMetadata(_thisType.Name));

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        #endregion

        public FormContent()
        {
            DefaultStyleKey = typeof(FormContent);
            Resources.Source = new Uri("/SilverlightControls;component/Designer/Themes/Generic.xaml", UriKind.Relative);
        }


        #region Overrides
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _layoutRoot = (ScrollViewer)GetTemplateChild("LayoutRoot");
            _mainGrid = (Grid)GetTemplateChild("MainGrid");
            _mainGrid.Drop += _mainGrid_DragEnter;
        }

        void _mainGrid_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data != null)
            {
                try
                {
                    FileInfo[] files = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
                    if (files.Length > 0)
                    {
                        foreach (FileInfo fi in files)
                        {
                            CreatePhoto(fi);
                        }
                        return;
                    }
                }
                catch{}
            }
        }

        #endregion

        private void CreatePhoto(FileInfo fi)
        {
            using (Stream stream = fi.OpenRead())
            {
                try
                {
                    // Decode the image bits
                    BitmapImage bi = null;

                    try
                    {
                        bi = new BitmapImage();
                        bi.SetSource(stream);
                    }
                    catch (OutOfMemoryException)
                    {
                        MessageBox.Show("Out of memory");
                        return;
                    }
                    catch (Exception)
                    {
                        // Probably came here because the image isn't valid; ignore
                        return;
                    }

                    // Compute the image dimensions
                    double cx = (double)bi.PixelWidth;
                    double cy = (double)bi.PixelHeight;

                    if (cx >= cy)
                    {
                        // Set width to 400 and compute height
                        cy *= 400.0 / cx;
                        cx = 400.0;
                    }
                    else
                    {
                        // Set width to 300 and compute height
                        cy *= 300.0 / cx;
                        cx = 300.0;
                    }

                    // Create a WriteableBitmap the same size as the image to be displayed
                    Image image = new Image();
                    image.Source = bi;
                    image.Width = cx;
                    image.Height = cy;

                    // Add the photo to the scene
                    _mainGrid.Children.Add(image);
                }
                catch (Exception)
                {
                    // Ignore exceptions resulting from drops of non-image files
                }
            }
        }

    }
}
